<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/16
 * Time: 0:54
 */

namespace app\lib;


use think\Db;

class SendTemplate
{
    protected $appid;
    protected $appsecret;
    protected $orderid; //订单id
    protected $access_token;
    protected $tpl; //模板id
    protected $pid;
    protected $openid;

    public function __construct($orderid,$openid = [],$pid=0,$op =true)
    {
        $this->appid = 'wx75bbccf096140543';
        $this->appsecret="e0d2be1c99791809c08b3127013959f6";
        $this->orderid=$orderid;
        $this->pid=$pid;
        if ($op ==true ){
            if (!empty($openid)){
                $this->openid = $openid;
            }else{
                 $this->getopenid();
            }
        }
        $this->access_token = cache('access_token');
        if (empty($this->access_token)){
            $this->getAccessToken();
        }

    }

    public function getopenid(){
        $data = [];
//        if ( $this->pid){//如果是分配订单
//            $wxopenid = db('member')->where(['pid'=> $this->pid,'iswork'=>1,'prohibit'=>1,'user_type'=>['in','2,3'],'step'=>['in','2,4']])->field('wxopenid')->select();
//            $data = array_column($wxopenid,'wxopenid');
//        }else{
//            //如果是新订单
            $order = Db::name('orders') ->where('order_mun',$this->orderid)->find();

            $user = db('member')
                ->where(['step'=>['in','2,4'],'iswork'=>1,'prohibit'=>1])
                ->field('wxopenid,xian,fenleiid')
                ->select();
//        $f = fopen('122222.text','a');
//        fwrite($f,json_encode($user));
//        fclose($f);
            foreach ($user as $v ){
                $area = explode(',', $v['xian']);
                $fenlei = explode(',',$v['fenleiid']);
                if (in_array($order['fenlei_id'],$fenlei)){
                    if (in_array($order['county'],$area)){
                        $data[] = $v['wxopenid'];
                    }
                }

            }
//        }
//        $f = fopen('1111.text','a');
//        fwrite($f,json_encode($data));
//        fclose($f);

        $this->openid = $data;
    }

    //获取access_token
    public function getAccessToken(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
        $json_token = $this->http_request($url);
        $access_token=json_decode($json_token,true);
        cache('access_token',$access_token['access_token'],7000);
        $this->access_token = cache('access_token');
        return $access_token['access_token'];
    }

    //post请求
    protected function http_request($url,$data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    //模板id
    public function toDoSend($template_id,$openid='',$type=1){
        switch($template_id){
            case 1:
                $this->tpl = "2lepAC_QSZ87SDpLmUo5S0OjUz12CLHZy6F5zCxXX48";//新订单通知
                $this->tpl($openid);
                break;
            case 2:
                $this->tpl ="u6RvlFiS8Ncl8rB7e9ggH1JTk5Qt4DNIvbZAr1fD4Ak";//用户取消订单或者更换师傅
                $this->quxiao($openid,$type);
                break;
            case 3:
                $tpl="esK5kFS8BHx6EiDJ2mkszKsijTU5TJKDyEEuqEessHY";//任务通知
                break;
            case 4:
                $tpl="mtklmdaJ2TCWOS8Taoxjm15bVFRa0Rj5GtdVqvPlLq0";//订单完成通知
                break;
            case 5:
                $tpl="pF0szsKuAh2u7ziqH3Im0GscRwrXaUNwXGrUNZKYHy8";//任务完成通知
                break;
            case 2:
                $tpl="pXFC-Lc4TgiAl-nQWMMbD7eLoi25SIWgSU3IXrcKcmw";//订单待支付提醒
                break;
            default:
                $tpl = '';
                break;

        }


    }
    /**
     * 订单取消通知
     * u6RvlFiS8Ncl8rB7e9ggH1JTk5Qt4DNIvbZAr1fD4Ak
     *
    您好，您预订的家政服务取消成功
    订单编号：20140901CC38AAB
    服务内容：宅洁士居家保洁-4小时
    点击'详细'查看完整信息

    {{first.DATA}}
    订单编号：{{keyword1.DATA}}
    服务内容：{{keyword2.DATA}}
    {{remark.DATA}}
     */
    public function quxiao($openid,$type){
        $quxiao = \db('quxiaoorder')->where('order_mun',$this->orderid)->limit(1)->order('id desc')->select();
        if ($type == 1){
            $str = "您好，您的订单用户已申请更换师傅";
        }
        if ($type ==2){
            $str = "您好，您的订单用户已申请退款";
        }
        $template=array(
            'touser'=>$openid,
            'template_id'=>  $this->tpl,
//            'url'=>"https://wukongweixiu.cn/index/account/jiedan/order_mun/". $this->orderid,
            'topcolor'=>"#7B68EE",
            'data'=>array(
                'first'=>array('value'=>urlencode($str),'color'=>"#000000"),
                'keyword1'=>array('value'=>urlencode($this->orderid),'color'=>'#000000'),
                'keyword2'=>array('value'=>urlencode($quxiao[0]['quxiao_remake']),'color'=>'#000000'),
            )
        );
        $json_template=json_encode($template);
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
        $res=$this->http_request($url,urldecode($json_template));
//        print_r($res);
    }

    /**
     * 组装新订单数据
     *
     *格式
        您好，您收到了一个新订单，请尽快接单处理
        订单编号：WX02302301
        客户昵称：达芙妮女士
        订单价格：200元
        订单标题：帮我的孩子找英语家教
        订单截止时间：2015-04-10 23:00
        点击查看订单详情
     */
    protected function tpl($openid){
        $data = db('orders')->where('order_mun',$this->orderid)->find();
        $openids = $this->openid;
        if ($openid != ''){
            unset($openids['$openid']);
        }elseif (empty($openids)){
            return;
        }

        foreach ($openids as $value){
            $template=array(
                'touser'=>$value,
                'template_id'=>  $this->tpl,
                'url'=>"https://wukongweixiu.cn/index/account/jiedan/order_mun/". $this->orderid,
                'topcolor'=>"#7B68EE",
                'data'=>array(
                    'first'=>array('value'=>urlencode("您好，您收到了一个新订单，请尽快接单处理"),'color'=>"#000000"),
                    'keyword1'=>array('value'=>urlencode($data['order_mun']),'color'=>'#000000'),
                    'keyword2'=>array('value'=>urlencode($data['name']),'color'=>'#000000'),
                    'keyword3'=>array('value'=>urlencode($data['price']),'color'=>'#000000'),
                    'keyword4'=>array('value'=>urlencode($data['goods_name']),'color'=>'#000000'),
//                    'keyword5'=>array('value'=>urlencode(date('Y-m-d H:i:s')),'color'=>'#000000'),
                )
            );

            $json_template=json_encode($template);
            $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
            $res=$this->http_request($url,urldecode($json_template));
//            $res = json_decode($res,true);
//            if ($res['errcode'] == 0){
//                return true;
//            }else{
//                return false;
//            }
        }

    }

    /*
     * 入驻申请提醒
     * 6TwF4KvuCJryLTENT41a0TV4uOLE0ytT0flBiBhsz4U
     {{first.DATA}}
        时间：{{keyword1.DATA}}
        内容：{{keyword2.DATA}}
        {{remark.DATA}}
*/
    public function rurzhu(){

    }

    /*
    新预约订单提醒
H5HPzXKOCHUGh31bDEY_M5Qmz8QGw5MOxbEmGQ_2_yE
{{first.DATA}}
预约人：{{keyword1.DATA}}
预约项目：{{keyword2.DATA}}
预约时间：{{keyword3.DATA}}
联系电话：{{keyword4.DATA}}
{{remark.DATA}}

尾款支付通知
    rtRcpYWR9EOxqg2pDrXOJo4pVSfvypEmqXkJuLwzT
    {{first.DATA}}
订单编号：{{keyword1.DATA}}
商品名称：{{keyword2.DATA}}
{{remark.DATA}}

     */


}